/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.opgea.qms.dao.impl;

import com.opgea.qms.dao.LoginDAO;
import com.opgea.qms.domain.entities.Login;
import com.opgea.qms.domain.entities.LoginPK;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Ramesh
 */
@Repository
@Transactional
public class LoginDAOImpl implements LoginDAO {

    //private Session session = HibernateUtil.getSessionFactory().openSession();
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public Login create(Login login) {
       Session session = sessionFactory.openSession();
       Transaction tx = session.getTransaction();
       tx.begin();
       session.save(login);
       tx.commit();
       return login;
    }

    @Override
    public Login update(Login login) {
        sessionFactory.openSession().update(login);
        return login;
    }

    
    @Override
    public Login find(String loginId) {
        /*
        Query query =  sessionFactory.openSession().getNamedQuery("Login.findByLoginId");
        query.setParameter("loginId", loginId);
        */ 
        
        Session session = sessionFactory.openSession();
        Query query = session.createQuery("SELECT l FROM Login l WHERE l.loginId = '"+loginId+"'");
        Login login = null;
        if(query.list().size() > 0){
            login = (Login) query.list().get(0);
        }


        return login;
    }

    @Override
    public List<Login> findAll() {
        List<Login> logins = sessionFactory.openSession().createQuery("from Login").list();
        return logins;
    }
    
    @Override
    public Login delete(String loginId) {
        Login login = this.find(loginId);
        sessionFactory.openSession().delete(login);
        return login;
    }
    
}
